//
//  XPContactGroupViewController.m
//  QQ
//
//  Created by nhope on 2017/4/26.
//  Copyright © 2017年 xiaopin. All rights reserved.
//

#import "XPContactGroupViewController.h"
#import "XPContactHeaderView.h"
#import "XPContactCellView.h"
#import "XPContactGroupModel.h"
#import "XPContactItemModel.h"

@interface XPContactGroupViewController ()<NSOutlineViewDataSource, NSOutlineViewDelegate>

@property (weak) IBOutlet NSOutlineView *outlineView;
/// 分组信息
@property (nonatomic, strong) NSArray<XPContactGroupModel *> *groups;

@end

@implementation XPContactGroupViewController

#pragma mark - Lifecycle

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.wantsLayer = YES;
    self.view.layer.backgroundColor = rgbColor(253.0, 253.0, 253.0).CGColor;
}

#pragma mark - <NSOutlineViewDataSource>

- (NSInteger)outlineView:(NSOutlineView *)outlineView numberOfChildrenOfItem:(id)item {
    if (nil == item) {
        return self.groups.count;
    }
    if ([item isKindOfClass:[XPContactGroupModel class]]) {
        return [(XPContactGroupModel*)item contacts].count;
    }
    return 0;
}

- (BOOL)outlineView:(NSOutlineView *)outlineView isItemExpandable:(id)item {
    return [item isKindOfClass:[XPContactGroupModel class]];
}

- (id)outlineView:(NSOutlineView *)outlineView child:(NSInteger)index ofItem:(id)item {
    if (nil == item) {
        return self.groups[index];
    }
    if ([item isKindOfClass:[XPContactGroupModel class]]) {
        XPContactGroupModel *group = (XPContactGroupModel *)item;
        return group.contacts[index];
    }
    return nil;
}

#pragma mark - <NSOutlineViewDelegate>

- (NSView *)outlineView:(NSOutlineView *)outlineView viewForTableColumn:(NSTableColumn *)tableColumn item:(id)item {
    if ([item isKindOfClass:[XPContactGroupModel class]]) {
        XPContactHeaderView *view = (XPContactHeaderView*)[outlineView makeViewWithIdentifier:@"HeaderCell" owner:nil];
        [view showForGroupModel:item];
        return view;
    }
    if ([item isKindOfClass:[XPContactItemModel class]]) {
        XPContactCellView *cell = (XPContactCellView*)[outlineView makeViewWithIdentifier:@"ContactCell" owner:nil];
        [cell showForContactInfomation:item];
        return cell;
    }
    return nil;
}

- (void)outlineViewSelectionDidChange:(NSNotification *)notification {
    NSOutlineView *outlineView = (NSOutlineView *)notification.object;
    NSInteger index = outlineView.selectedRow;
    if (-1 == index) return;
    id model = [outlineView itemAtRow:index];
    [outlineView deselectRow:index];
    
    if ([model isKindOfClass:[XPContactGroupModel class]]) {
        BOOL flag = [outlineView isItemExpanded:model];
        flag ? [outlineView collapseItem:model] : [outlineView expandItem:model];
    } else {
        // TODO:选中联系人,更新右侧联系人的信息
        XPContactItemModel *contact = (XPContactItemModel *)model;
        NSLog(@"%@", contact.username);
    }
}

- (CGFloat)outlineView:(NSOutlineView *)outlineView heightOfRowByItem:(id)item {
    if ([item isKindOfClass:[XPContactGroupModel class]]) {
        return 27.0;
    }
    return 60.0;
}

#pragma mark - Actions

/// 添加好友
- (IBAction)addFriendsButtonAction:(NSButton *)sender {
    // TODO:测试
    NSViewController *vc = [[NSViewController alloc] init];
    vc.view = [[NSView alloc] init];
    vc.view.wantsLayer = YES;
    vc.view.layer.backgroundColor = [[NSColor orangeColor] CGColor];
    vc.view.frame = NSMakeRect(0.0, 0.0, CGRectGetWidth(sender.frame), 100.0);
    
    NSPopover *popover = [[NSPopover alloc] init];
    popover.behavior = NSPopoverBehaviorTransient;
    popover.appearance = [NSAppearance appearanceNamed:NSAppearanceNameAqua];
    popover.contentViewController = vc;
    [popover showRelativeToRect:sender.bounds ofView:sender preferredEdge:NSRectEdgeMaxY];
}

#pragma mark - setter & getter

- (NSArray<XPContactGroupModel *> *)groups {
    if (nil == _groups) {
        // TODO:模拟分组数组
        NSMutableArray *groupArray = [NSMutableArray array];
        for (int i=0; i<5; i++) {
            XPContactGroupModel *group = [[XPContactGroupModel alloc] init];
            group.name = randomString(10);
            group.peopleNumber = arc4random_uniform(100);
            group.onlinePeopleNumber = arc4random_uniform((unsigned int)(group.peopleNumber+1));
            [groupArray addObject:group];
            
            // 模拟分组成员数据
            NSMutableArray *contactArray = [NSMutableArray array];
            for (int j=0; j<group.peopleNumber; j++) {
                XPContactItemModel *item = [[XPContactItemModel alloc] init];
                item.username = randomString(arc4random_uniform(10));
                item.remarkName = [@"Remark " stringByAppendingString:item.username];
                item.latestMessage = [NSString stringWithFormat:@"%@ %d:%d", randomString(arc4random_uniform(30)),i,j];
                item.state = arc4random_uniform(4);
                [contactArray addObject:item];
            }
            
            // 模拟在线用户排序,在线>离开>离线/隐身
            [contactArray sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
                XPContactItemModel *item1 = obj1;
                XPContactItemModel *item2 = obj2;
                if (item1.state == item2.state) {
                    return NSOrderedSame;
                }
                if (item1.state == XPUserStateOnline) {
                    return NSOrderedAscending;
                }
                if (item1.state == XPUserStateLeave) {
                    if (item2.state == XPUserStateOnline) {
                        return NSOrderedDescending;
                    }
                    return NSOrderedAscending;
                }
                return NSOrderedDescending;
            }];
            
            group.contacts = [NSArray arrayWithArray:contactArray];
        }
        _groups = [NSArray arrayWithArray:groupArray];
    }
    return _groups;
}


@end
